#pragma once

/*
    实用工具类：
        1、获取系统时间
        2、判断文件是否存在
        3、获取文件搜索在路径
        4、创建目录
*/

#include <iostream>
#include <string>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

namespace Log
{
    namespace utility
    {
        class Date
        {
        public:
            static size_t now()
            {
                return (size_t)time(nullptr);
            }
        };

        class File
        {
        public:
            static bool exists(const std::string &pathname)
            {
                struct stat st;
                return stat(pathname.c_str(), &st) == 0;
            }

            static std::string path(const std::string &pathname)
            {
                if (pathname.empty())
                    return ".";

                size_t pos = pathname.find_last_of("/\\");
                if (pos == std::string::npos)
                    return ".";

                return pathname.substr(0, pos + 1);
            }

            static void createDirectory(const std::string &pathname)
            {
                if (pathname.empty())
                    return;
                if (exists(pathname))
                    return;

                size_t pos = 0, idx = 0;
                while (idx < pathname.size())
                {
                    pos = pathname.find_first_of("/\\", idx);

                    // 没查找到分隔符在当前路径下直接创建
                    if (pos == std::string::npos)
                    {
                        mkdir(pathname.c_str(), 0777);
                        return;
                    }

                    std::string parent_dir = pathname.substr(0, pos + 1);
                    if (exists(parent_dir))
                    {
                        // 当前路径下存在此目录时，提前更新下次查找位置
                        idx = pos + 1;
                        continue;
                    }

                    mkdir(parent_dir.c_str(), 0777);
                    idx = pos + 1;
                }
            }
        };
    }
}